package me.zhengjie.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@DependsOn({"redisUtils"})
public class VxMsg {

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private RedisUtils redisUtils;
    @Value("${weixin.tokenUrl}")
    private String tokenUrl;
    @Value("${weixin.openIdUrl}")
    private String openIdUrl;
    @Value("${weixin.phoneUrl}")
    private String phoneUrl;

    @Value("${weixin.appID}")
    private String appID;
    @Value("${weixin.appSecret}")
    private String appSecret;

    @Value("${weixinNew.appID}")
    private String newAppID;
    @Value("${weixinNew.appSecret}")
    private String newAppSecret;


    /**
     * 获取微信toekn
     * @return
     */
    public String getVxToken(){
        String jsonStr = restTemplate.getForEntity(tokenUrl+"?appid={1}&secret={2}&grant_type={3}", String.class, appID,appSecret,"client_credential").getBody();
        log.info(jsonStr);
        JSONObject json = JSONUtil.parseObj(jsonStr);
        String accesToken = json.getStr("access_token");
        redisUtils.set("acces_token",accesToken,6000, TimeUnit.SECONDS);
        return accesToken;
    }

    public String vxLogin(String code){
        JSONObject postData = new JSONObject();
        postData.put("appid", appID);
        postData.put("secret", appSecret);
        postData.put("js_code", code);
        postData.put("grant_type", "authorization_code");
        String jsonStr = restTemplate.getForEntity(openIdUrl+"?appid={1}&secret={2}&js_code={3}&grant_type={4}", String.class, appID,appSecret, code,"authorization_code").getBody();
        return jsonStr;
    }



    public String vxPhoneUrl(String code){
        String accesToken;
        if(redisUtils.hasKey("acces_token")){
            log.info("acces_token存在");
            accesToken = (String) redisUtils.get("acces_token");
        }else{
            accesToken = getVxToken();
        }
        log.info("acces_token:"+accesToken);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", code);
        log.info("调用获取信息接口");
        return restTemplate.postForObject(phoneUrl+"?access_token="+accesToken, paramMap, String.class);
    }

    public String getNewVxToken(){
        String jsonStr = restTemplate.getForEntity(tokenUrl+"?appid={1}&secret={2}&grant_type={3}", String.class, newAppID,newAppSecret,"client_credential").getBody();
        log.info(jsonStr);
        JSONObject json = JSONUtil.parseObj(jsonStr);
        String accesToken = json.getStr("access_token");
        redisUtils.set("new_acces_token",accesToken,6000, TimeUnit.SECONDS);
        return accesToken;
    }

    public String newVxLogin(String code){
        JSONObject postData = new JSONObject();
        postData.put("appid", newAppID);
        postData.put("secret", newAppSecret);
        postData.put("js_code", code);
        postData.put("grant_type", "authorization_code");
        String jsonStr = restTemplate.getForEntity(openIdUrl+"?appid={1}&secret={2}&js_code={3}&grant_type={4}", String.class, newAppID,newAppSecret, code,"authorization_code").getBody();
        return jsonStr;
    }

    public String newVxPhoneUrl(String code){
        String accesToken;
        if(redisUtils.hasKey("new_acces_token")){
            log.info("new_acces_token存在");
            accesToken = (String) redisUtils.get("new_acces_token");
        }else{
            accesToken = getNewVxToken();
        }
        log.info("new_acces_token:"+accesToken);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", code);
        log.info("新调用获取信息接口");
        return restTemplate.postForObject(phoneUrl+"?access_token="+accesToken, paramMap, String.class);
    }


    /**
     * 新订单提醒
     * @param touser
     * @param name  客户名称
     * @param phone 客户电话
     * @param address 客户地址
     * @param amount 订单金额
     * @param remark 备注
     * @return
     */
    public String sendOrderMsg(String touser,Integer id,String name,String phone,String address,String amount,String remark) {
        JSONObject postData = new JSONObject();
        postData.put("touser", touser);
        postData.put("template_id", "waPFm20biXmTy8lCooCLbq5huAQWr4-_9seb292Lh1c");
        postData.put("page","pages/order_new/edit?notice=true&id="+id);
        JSONObject data = new JSONObject();
        data.put("thing12", new JSONObject().put("thing12", StringUtils.isNotBlank(name)?name:"test"));
        data.put("phone_number6", new JSONObject().put("value",  StringUtils.isNotBlank(phone)?phone:"test"));
        data.put("thing7", new JSONObject().put("value",  StringUtils.isNotBlank(address)?address:"test"));
        data.put("amount4", new JSONObject().put("value", StringUtils.isNotBlank(amount)?amount:"test"));
        data.put("thing2", new JSONObject().put("value",  StringUtils.isNotBlank(remark)?remark:"test"));
        postData.put("data",data);
        log.info("输出新订单提醒json ={}",postData);
        return this.sendMessage(postData.toString());
    }

    /**
     * 新跟进提醒
     * @param touser
     * @param name 提醒人姓名
     * @param thing4 项目名称
     * @param thing5 任务名称
     * @param date3 预约时间
     * @param thing2 温馨提示
     * @return
     */
    public String sendFollowMsg(String touser,Integer id,String name,String thing4,String thing5,String date3,String thing2) {
        JSONObject postData = new JSONObject();
        postData.put("touser", touser);
        postData.put("template_id", "aI8EdC0wVg_P0t1RyK2IpfL53Np2xTPBwO3xRP6Wy8A");
        postData.put("page","pages/follow/edit?notice=true&id="+id);
        JSONObject data = new JSONObject();
        data.put("name1", new JSONObject().put("value",  StringUtils.isNotBlank(name)?name:"test"));
        data.put("thing4", new JSONObject().put("value",  StringUtils.isNotBlank(thing4)?thing4:"test"));
        data.put("thing5", new JSONObject().put("value",  StringUtils.isNotBlank(thing5)?thing5:"test"));
        data.put("date3", new JSONObject().put("value",  StringUtils.isNotBlank(date3)?date3:"test"));
        data.put("thing2", new JSONObject().put("value",  StringUtils.isNotBlank(thing2)?thing2:"test"));
        postData.put("data",data);
        log.info("输出新跟进提醒json ={}",postData);
        return this.sendMessage(postData.toString());
    }

    /**
     * 新客户提醒
     * @param touser
     * @param thing1 提醒内容
     * @param time2 提醒时间
     * @return
     */
    public String sendCustomerMsg(String touser,Integer id,Integer type,String thing1,String time2) {
        JSONObject postData = new JSONObject();
        postData.put("touser", touser);
        postData.put("template_id", "iytYYGG1WF6CM_fmoXzEbCU0JxE_58FWeeg5gasoTPc");
        postData.put("page","pages/customer/detail?notice=true&id="+id+"&type="+type);
        JSONObject data = new JSONObject();
        data.put("thing1", new JSONObject().put("value", StringUtils.isNotBlank(thing1)?thing1:"test"));
        data.put("time2", new JSONObject().put("value", StringUtils.isNotBlank(time2)?time2:"test"));
        postData.put("data",data);
        log.info("输出新客户提醒json ={}",postData);
        return this.sendMessage(postData.toString());
    }

	public String sendMessage(String msg) {
		log.info("发送统一模板消息:" + msg);
        String accesToken;
        if(redisUtils.hasKey("acces_token")){
            log.info("acces_token存在");
            accesToken = (String) redisUtils.get("acces_token");
        }else{
            log.info("acces_token不存在");
            String jsonStr = restTemplate.getForEntity(tokenUrl+"?appid={1}&secret={2}&grant_type={3}", String.class, appID,appSecret,"client_credential").getBody();
            log.info(jsonStr);
            JSONObject json = JSONUtil.parseObj(jsonStr);
            accesToken = json.getStr("access_token");
            redisUtils.set("acces_token",json.getStr("access_token"),6000,TimeUnit.SECONDS);
        }
		String requestUrl = String.format("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s",accesToken);
		log.info("发送统一模板消息到:" + requestUrl);
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		// 请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

		HttpEntity<String> requestEntity = new HttpEntity<String>(msg, headers);

		// 进行网络请求,访问url接口
		ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, HttpMethod.POST, requestEntity,
				String.class);
		log.info("发送统一模板消息后接受数据:" + responseEntity);
        String sessionData = "";
		if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
            sessionData = responseEntity.getBody();
		}
		return sessionData;
	}
}
